/**
 * Created by ascainiao on 2014/11/22.
 * 邮箱405076856@qq.com
 * CreateJS中文网 https://www.createjs.cc
 * QQ交流群：320648191
 * 
 */
import createjs from 'createjs-ts'
import cjs=createjs
export default class DoubleFingerScaleHelper{
    private target:cjs.DisplayObject;
    private mouseDownHandler:any;
    private pressMoveHandler:any;
    constructor(target:cjs.DisplayObject,ratio=1,mouseDownCallback?:any,pressMoveCallback?:any){
        this.target=target
        let d=0,scale=1
        //
        this.mouseDownHandler=target.stage.on('stagemousedown',(e:any)=>{
            //console.log(e)
            const evt=e.nativeEvent as TouchEvent;
            //console.log(evt)
            if(evt.touches.length>1){
                //console.log('more than one')
                const p0=new cjs.Point(evt.touches[0].clientX*ratio,evt.touches[0].clientY*ratio)
                const p1=new cjs.Point(evt.touches[1].clientX*ratio,evt.touches[1].clientY*ratio)
                const p2=new cjs.Point((p0.x+p1.x)/2,(p0.y+p1.y)/2)
                const reg=target.globalToLocal(p2.x,p2.y)
                const localp=target.parent.globalToLocal(p2.x,p2.y)
                scale=target.scale
                target.setTransform(localp.x,localp.y,scale,scale,0,0,0,reg.x,reg.y)
                d=Math.sqrt(Math.pow(p0.x-p1.x,2)+Math.pow(p0.y-p1.y,2))
                
                mouseDownCallback&&mouseDownCallback(p0,p1)
            }else{
                console.log('only one')
            }
        })
        //
        this.pressMoveHandler=target.stage.on('stagemousemove',(e:any)=>{
            const evt=e.nativeEvent as TouchEvent;
            if(evt.touches?.length>1){
                //console.log('more than one')
                const p0=new cjs.Point(evt.touches[0].clientX*ratio,evt.touches[0].clientY*ratio)
                const p1=new cjs.Point(evt.touches[1].clientX*ratio,evt.touches[1].clientY*ratio)
                const p2=new cjs.Point((p0.x+p1.x)/2,(p0.y+p1.y)/2)
                const localp=target.parent.globalToLocal(p2.x,p2.y)
                const t=Math.sqrt(Math.pow(p0.x-p1.x,2)+Math.pow(p0.y-p1.y,2))
                const f=t-d
                target.scale=scale+f/1000;
                target.x=localp.x;
                target.y=localp.y;
                pressMoveCallback&&pressMoveCallback(p0,p1)
            }else{
                console.log('only one')
            }
        })
    }
    //销毁
    destroy():void{
        this.target.stage.off('stagemousedown',this.mouseDownHandler)
        this.target.stage.off('stagemousemove',this.pressMoveHandler)
    }
}